<!-- 操作记录列表页 -->
<template>
	<view >
		<!-- 搜索框 -->
		<view><nav-search @methods="searcher" :showBack="true" :placeholder="'请输入要查询的ID/名称'"></nav-search></view>
		<!-- 筛选框 -->
		<u-dropdown class="fa-dropdown" ref="uDropdown">
			<u-dropdown-item :title="dropdownTitle.opt || '操作类型'">
				<view class="slot-content">
					<view class="select-box">
						<view v-for="(opt, index) in operateList"
							:key="index"
							class="select-item item-3 text-ellipsis" 
							:class="selectOn({'opt': opt.DictKey})"
							@click="addOrRm({'opt': opt.DictKey})"
							>{{opt.DictValue}}
						</view>
					</view>
					<view class="footer-padding"></view>
					<view class="footer">
						<view class="reset" @click="reset('opt')"><image src="../../../static/images/clear.svg"></image>重置</view>
						<view class="changer" @click="filterUpdater">查看</view>
					</view>
				</view>
			</u-dropdown-item>
			<u-dropdown-item :title="dropdownTitle.date || '操作时间'">
				<view class="slot-content">
					<view class="tips">常用时间</view>
					<view class="select-box" style="padding-bottom: 0;">
						<view class="select-item item-4" @click="selectDate('today')" :class="selected.date === 'today' ? 'selected' : ''">今天</view>
						<view class="select-item item-4" @click="selectDate('weekly')" :class="selected.date === 'weekly' ? 'selected' : '' ">最近一周</view>
						<view class="select-item item-4" @click="selectDate('monthly')" :class="selected.date === 'monthly' ? 'selected' : '' ">最近一个月</view>
						<view class="select-item item-4" @click="selectDate('all')" :class="selected.date === 'all' ? 'selected' : '' ">全部</view>
					</view>
					<view class="tips" style="padding-top: 0;">自定义时间</view>
					<!-- 自定义日期选择 -->
					<view class="select-box" style="padding-top: 0;">
						<view class="select-item item-2 date" @click="show.datePicker = true">{{dateRange.start || '起始时间'}}</view>
						<text class="date" style="line-height: 64rpx;">至</text>
						<view class="select-item item-2 date" @click="show.datePicker = true">{{dateRange.end || '结束时间'}}</view>
					</view>
					<view class="footer-padding"></view>
					<view class="footer">
						<view class="reset" @click="reset('time')"><image src="../../../static/images/clear.svg"></image>重置</view>
						<view class="changer" @click="filterUpdater">查看</view>
					</view>
				</view>
			</u-dropdown-item>
			<u-dropdown-item :title="dropdownTitle.org || '房产'">
				<view class="slot-content">
					<view class="select-box">
						<view v-for="(org, index) in orgList"
							:key="index"
							class="select-item item-3 text-ellipsis" 
							:class="selectOn({'org': org.ID})"
							@click="addOrRm({'org': org.ID})"
							>{{org.OrgName}}
						</view>
					</view>
					<view class="footer-padding"></view>
					<view class="footer">
						<view class="reset" @click="reset('org')"><image src="../../../static/images/clear.svg"></image>重置</view>
						<view class="changer" @click="filterUpdater">查看</view>
					</view>
				</view>
			</u-dropdown-item>
			<u-dropdown-item :title="dropdownTitle.category || '资产类型'">
				<view class="slot-content">
					<view class="tips">一级分类</view>
					<view class="select-box">
						<view v-for="(parent, index) in categoryDict.parent"
							:key="index"
							class="select-item item-3 text-ellipsis" 
							:class="selectOn({'category': parent.DictItemKey})"
							@click="addOrRm({'category': parent.DictItemKey})"
							>{{parent.DictItemValue}}
							<u-badge type="primary" :offset="[-10,-10]" :count="badgeCount(parent.DictItemKey)"></u-badge>
						</view>
					</view>
					<view class="tips" v-show="childrenList.length">二级分类</view>
					<view class="select-box">
						<view v-show="childrenList.length" class="select-item item-3 text-ellipsis" :class="categorySelectAllHover" @click="categorySelectAll">全部</view>
						<view v-for="(child, index) in childrenList"
							:key="index"
							class="select-item item-3 text-ellipsis" 
							:class="selectOn({'category': child.DictItemKey, 'parent': child.DictTypeKey})"
							@click="addOrRm({'category': child.DictItemKey, 'parent': child.DictTypeKey})"
							>{{child.DictItemValue}}
						</view>
					</view>
					<view class="footer-padding"></view>
					<view class="footer">
						<view class="reset" @click="reset('category')"><image src="../../../static/images/clear.svg"></image>重置</view>
						<view class="changer" @click="filterUpdater">查看</view>
					</view>
				</view>
			</u-dropdown-item>
		</u-dropdown>
		<!-- 列表框 -->
		<view class="list-wrap">
			<view class="record-item" @click="toDetail(item.Guid)" v-for="item in recordList" :key="item.Guid">
				<view class="title flex-between">
					<view style="max-width: 30%;" class="text-ellipsis">{{item.EpcId}}</view>
					<view>{{item.CreateTime | dateFormat}}</view>
					<view style="color: #4F5053;"><span class="red">{{item.OprTypeText}}</span></view>
				</view>
				<view class="content">
					<view style="width: 25%;text-align: center;"><image :src="item.img"></image></view>
					<view style="width: 70%;">
						<view style="font-size: 28rpx;
									font-family: PingFangSC-Medium, PingFang SC;
									font-weight: 500;
									padding-bottom: 10rpx;
									color: #2A2A2A;">{{item.Name}}</view>
						<view style="font-size: 24rpx;
									font-family: PingFangSC-Regular, PingFang SC;
									font-weight: 400;
									padding-bottom: 10rpx;
									color: #4F5053;">{{item.OrgName}}</view>
						<view class="flex-between" style="font-size: 24rpx;
									font-family: PingFangSC-Regular, PingFang SC;
									font-weight: 400;
									padding-bottom: 10rpx;
									color: #4F5053;">
							<view>{{item.TypeText}}</view>
							<view style="padding-right: 20rpx;">1件</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 日期 -->
		<u-calendar v-model="show.datePicker" mode="range" @change="calenderHandler"></u-calendar>
		<!-- 加载更多 -->
		<u-loadmore v-show="recordList.length > 0" :status="loadMoreStatus" @loadmore="loadMore" bg-color="#F6F8FB" />
		<view style="width: 100%;height: 30rpx;background-color: #F6F8FB;"></view>
	</view>
</template>

<script>
	import navSearch from '@/components/fa-nav-search/fa-nav-search.vue'
	export default {
		components: {navSearch},
		data() {
			return {
				recordList: [],
				show: {
					datePicker: false
				},
				dateRange: {
					start: "",
					end: ""
				},
				selected: {
					date: "",  // 时间
					org: [],  // 房产
					category: {},  // 资产类别
					opt: [],  // 操作类型
				},
				orgList: [],
				categoryDict: {},
				categoryList: [],
				filterParams: {},
				noMore: false,
				loadMoreStatus: "loadmore",
				childrenList: [],  // 二级分类列表
				operateList: [],  // 操作类型列表
				filterParams: {
					PageIndex: 1,
					PageSize: 10,
					AssetName: ""
				},
				dropdownTitle: {
					opt: "",
					org: "",
					category: "",
					date: ""
				},
				selectCategoryCounter: {},
				categorySelectAllHover: ""
			}
		},
		onLoad() {
			// 获取房产列表
			this.$api.getOrgList().then(res => {
				this.orgList = res.data;
			});
			// 获取分类列表
			this.$api.getTypeStatusList({"ParentKey": "ASSET_TYPE", "PageIndex": 1, "PageSize": 10000}).then(res => {
				this.categoryDict = this.categoryConvertor(res.data.Data);
				this.categoryList = res.data.Data;
			});
			// 获取操作类型列表
			this.$api.getDictList({"DictType": "ITEM", "LangCode": "zh-CN", "ParentDictKey": "FASG_OPR_TYPE"}).then(res => {
				this.operateList = res.data;
			});
		},
		computed: {
			selectOn() {
				return ({category, org, opt, parent}) => {
					let target = category ? this.selected.category : org ? this.selected.org : this.selected.opt;
					let val = category || org  || opt;
					if (target.length !== undefined) {
						return target.indexOf(val) >= 0 ? 'selected' : '';
					} else {
						// 二级列表
						if (parent) {
							return target[parent][val] ? 'selected' : '';
						}
						// 一级列表
						if (this.categoryDict[val]) {
							// 有二级分类的
							return Object.keys(target[val] || {}).length > 0 ? 'selected' : '';
						}
						return target[val] ? 'selected' : '';
					}
				}
			},
			badgeCount() {
				return key => {
					if (!this.selected.category[key]) {
						return 0;
					}
					return Object.keys(this.selected.category[key]).length;
				}
			},
		},
		watch: {
			'filterParams': {
				deep: true,
				handler(newVal, oldVal) {
					this.$api.getOperationList(this.filterParams).then(res => {
						if (res.data) {
							res.data.Data.forEach(elem => {
								let img; 
								if (elem.ImgUrls) {
									img = elem.ImgUrls[0];
								}
								elem.img = img || "/static/images/nopic.png";
							});
							if (this.filterParams.PageIndex > 1) {
								this.recordList.push(...res.data.Data);
							} else {
								this.recordList = res.data.Data;
								
							}
							if (res.data.TotalPage === res.data.Page) {
								this.loadMoreStatus = "nomore";
								this.noMore = true;
							} else {
								this.loadMoreStatus = "loadmore";
								this.noMore = false;
							}
						} else {
							uni.showToast({title: "数据异常，请稍后再试", icon: "none"});
						}
					});
				},
				immediate: true
			},
		},
		methods: {
			searcher(ipt) {
				// 快捷搜索时清空已选的筛选数据
				this.dropdownTitle = {
					opt: "",
					org: "",
					category: "",
					date: ""
				}
				this.selected = {
					date: "",
					org: [],
					category: {},
					opt: []
				}
				this.filterParams = {
					PageIndex: 1,
					PageSize: 10,
					ConditionText: ipt
				}
			},
			calenderHandler(selectData) {
				this.dateRange.start = selectData.startDate;
				this.dateRange.end = selectData.endDate;
				this.selected.date = "";
			},
			selectDate(_type) {
				this.selected.date = _type;
				let now = new Date();
				switch(_type) {
					case "today":
						let today = this.dateFormat("YYYY-mm-dd", new Date());
						this.dateRange.start = today;
						this.dateRange.end = today;
						break;
					case "weekly":
						let lastWeek = new Date(now.getTime() - 1000 * 60 * 60 * 24 * 7);
						this.dateRange.start = this.dateFormat("YYYY-mm-dd", lastWeek);
						this.dateRange.end = this.dateFormat("YYYY-mm-dd", now);
						break;
					case "monthly":
						let lastMonth = new Date(now.getTime() - 1000 * 60 * 60 * 24 * 30);
						this.dateRange.start = this.dateFormat("YYYY-mm-dd", lastMonth);
						this.dateRange.end = this.dateFormat("YYYY-mm-dd", now);
						break;
					default:   // all
						this.dateRange.start = "";
						this.dateRange.end = "";
				}
			},
			dateFormat(fmt, date) {
			    let ret;
			    const opt = {
			        "Y+": date.getFullYear().toString(),        // 年
			        "m+": (date.getMonth() + 1).toString(),     // 月
			        "d+": date.getDate().toString(),            // 日
			        "H+": date.getHours().toString(),           // 时
			        "M+": date.getMinutes().toString(),         // 分
			        "S+": date.getSeconds().toString()          // 秒
			        // 有其他格式化字符需求可以继续添加，必须转化成字符串
			    };
			    for (let k in opt) {
			        ret = new RegExp("(" + k + ")").exec(fmt);
			        if (ret) {
			            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
			        };
			    };
			    return fmt;
			},
			categorySelectAll() {
				for (let key in this.selected.category) {
					if (this.childrenList[0].DictTypeKey === key) {
						this.childrenList.forEach(item => {this.selected.category[key][item.DictItemKey] = item.DictItemKey});
						this.categorySelectAllHover = 'selected';
						this.selectCategoryCounter[key] = this.childrenList.length;
					}
				}
				this.$nextTick(() => this.$forceUpdate());
			},
			addOrRm({category, org, opt, parent}) {
				let target = category ? this.selected.category : org ? this.selected.org : this.selected.opt;
				let val = category || org  || opt;
				if (target.length !== undefined) {
					let index = target.indexOf(val);
					if (index >= 0) {
						target.splice(index, 1);
					} else {
						target.push(val);
					}
				} else {
					if (parent) {
						if (!target[parent]) {
							target[parent] = {};
						}
						if (target[parent][val]) {
							delete target[parent][val];
							this.selectCategoryCounter[parent]--;
						} else {
							target[parent][val] = val;
							if (!this.selectCategoryCounter[parent]) {
								this.selectCategoryCounter[parent] = 0;
							}
							this.selectCategoryCounter[parent]++;
						}
						this.categorySelectAllHover = this.selectCategoryCounter[parent] && this.selectCategoryCounter[parent] === this.childrenList.length ? 'selected' : '';
					} else {
						this.childrenList = this.categoryDict[val] || [];
						this.categorySelectAllHover = this.selectCategoryCounter[val] && this.selectCategoryCounter[val] === this.childrenList.length ? 'selected' : '';
						if (this.categoryDict[val]) {
							if (!target[val]) {
								target[val] = {};
							}
						} else {
							if (target[val]) {
								delete target[val];
							} else {
								target[val] = {};
							}
						}
					}
					
					this.$nextTick(() => this.$forceUpdate());
				}
			},
			toDetail(detailId) {
				uni.navigateTo({url: `/pages/user/record/detail?detailId=${detailId}`});
			},
			filterUpdater() {
				let filter = JSON.parse(JSON.stringify(this.filterParams));
				filter.OrgGuids = this.selected.org.slice(0);
				filter.StartTime = this.dateRange.start ? new Date(this.dateRange.start.replace(/-/g, "/")).getTime() : null;
				filter.EndTime = this.dateRange.end ? new Date(this.dateRange.end.replace(/-/g, "/")).getTime() : null;
				if (filter.EndTime) {
					filter.EndTime += 1000 * (60 * 60 * 23 + 60 * 59 + 59);
				}
				filter.PageIndex = 1;
				let assetTypes = [];
				for (let key in this.selected.category) {
					assetTypes.push(key); 
					let child = this.selected.category[key];
					for (let childKey in child) {
						assetTypes.push(childKey);
					}
				}
				filter.AssetTypes = assetTypes;
				filter.OperationTypes = this.selected.opt.slice(0);
				this.filterParams = filter;
				
				this.dropdownTitle.opt = "";
				if (this.selected.opt.length > 0) {
					this.selected.opt.forEach(k => this.dropdownTitle.opt += this.operateList.find(item => item.DictKey === k).DictValue + ',');
					this.dropdownTitle.opt = this.dropdownTitle.opt.substr(0, this.dropdownTitle.opt.length - 1);
				}
				
				this.dropdownTitle.org = "";
				if (this.selected.org.length > 0) {
					this.selected.org.forEach(k => this.dropdownTitle.org += this.orgList.find(item => item.ID === k).OrgName + ',');
					this.dropdownTitle.org = this.dropdownTitle.org.substr(0, this.dropdownTitle.org.length - 1);
				}
				
				this.dropdownTitle.category = "";
				for (let key in this.selected.category) {
					this.dropdownTitle.category += this.categoryList.find(item => item.DictItemKey === key).DictItemValue + ',';
				}
				this.dropdownTitle.category = this.dropdownTitle.category.substr(0, this.dropdownTitle.category.length - 1);
				
				this.dropdownTitle.date = "";
				if (this.selected.date === 'all') {
					this.dropdownTitle.date = "全部";
				} else if (this.selected.date === 'weekly') {
					this.dropdownTitle.date = "最近一周";
				} else if (this.selected.date === 'monthly') {
					this.dropdownTitle.date = '最近一个月';
				} else if (this.selected.date === 'today') {
					this.dropdownTitle.date = "今天";
				} else if (this.dateRange.start) {
					this.dropdownTitle.date = "自定义时间";
				}
				this.$refs.uDropdown.close();
			},
			reset(_type) {
				switch(_type) {
					case "category": 
						this.childrenList = [];
						this.selected.category = {};
						this.selectCategoryCounter = {};
						this.categorySelectAllHover = "";
						break;
					case "opt":
						this.selected.opt = [];
						break;
					case "org":
						this.selected.org = [];
						break;
					default:   // time
						this.dateRange.start = "";
						this.dateRange.end = "";
						this.selected.date = "";
				}
				// this.filterUpdater();
				//
			},
			loadMore() {
				if (!this.noMore) {
					this.loadMoreStatus = "loading";
					this.filterParams.PageIndex = this.filterParams.PageIndex + 1;
				}
			},
			categoryConvertor(dictList) {
				// 排序后顶级分类在最前面
			    dictList = dictList.sort((a, b) => a.DictTypeKey.length - b.DictTypeKey.length);
				let list = {};
				let markParent = true;
				dictList.forEach(item => {
					if (!list[item.DictTypeKey]) {
						list[item.DictTypeKey] = [];
					}
					if (markParent) {
						list.parent = list[item.DictTypeKey];
						markParent = false;
					}
					list[item.DictTypeKey].push(item);
				});
				return list;
			}
		},
		onReachBottom() {
			this.loadMore();
		},
	}
</script>

<style lang="scss" scoped>
	.slot-content {
		min-height: 400rpx;
		background-color: #FFF;
		position: relative;
		.select-box {
			display: flex;
			flex-wrap: wrap;
			padding: 20rpx;
			max-height: 600rpx;
			overflow-y: auto;
			.select-item {
				height: 64rpx;
				background: #F6F8FB;
				border-radius: 2px;
				color: #2A2A2A;
				text-align: center;
				line-height: 64rpx;
				margin: 0 10rpx;
				padding: 0 6rpx;
				margin-bottom: 20rpx;
				position: relative;
				overflow: visible;
			}
			.selected {
				color: #2E73E5 !important;
				background: #ECF4FF;
			}
			.item-4 {
				width: 22% !important;
			}
			.item-3 {
				width: 30% !important;
			}
			.item-2 {
				width: 45% !important;
			}
			.date {
				font-size: 24rpx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #666666;
			}
		}
		.tips {
			font-size: 28rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 600;
			color: #2A2A2A;
			padding: 10rpx 20rpx;
		}
		.footer {
			position: absolute;
			bottom: 0;
			width: 100%;
			height: 120rpx;
			padding: 20rpx;
			display: flex;
			flex-wrap: wrap;
			image {
				width: 45rpx;
				height: 45rpx;
				vertical-align: middle;
				margin-right: 15rpx;
			}
		}
		.footer-padding {
			width: 100%;
			height: 120rpx;
		}
		.reset,
		.changer {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
		}
		.reset {
			width: 30%;
			font-size: 28rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #2A2A2A;
		}
		.changer {
			width: 70%;
			background: linear-gradient(310deg, #5BABF4 0%, #2E73E5 100%);
			border-radius: 20px;
			font-size: 32rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #FFFFFF;
		}
	}
	.list-wrap {
		min-height: 90vh;
		width: 100%;
		background-color: #F6F8FB;
		padding: 40rpx 20rpx;
		.record-item {
			width: 100%;
			height: 260rpx;
			background-color: #FFFFFF;
			overflow: hidden;
			margin: 20rpx 0;
			box-shadow: 0px 4px 12px 0px rgba(61, 76, 98, 0.12);
			border-radius: 4px;
			.title {
				margin: 20rpx;
				height: 60rpx;
				line-height: 60rpx;
				border-bottom: 1px solid #e2e2e2;
				font-size: 24rpx;
				font-family: Roboto-Regular, Roboto;
				font-weight: 400;
				color: #999999;
				span {
					padding: 5rpx 15rpx;
					border-radius: 4rpx;
					margin-left: 5rpx;
				}
				.green {
					background-color: #edfbf5;
					color: #58cf80;
				}
				.red {
					background-color: #fceeee;
					color: #e87070;
				}
			}
			.content {
				display: flex;
				flex-wrap: wrap;
				image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 8rpx;
				}
			}
		}
	} 

</style>
